<template>
  <div>
    <el-upload
      :file-list="fileList"
      class="upload-demo"
      :action="upload.action"
      :multiple="upload.multiple"
      :accept="upload.accept"
      :headers="upload.headers"
      :data="upload.data"
      :name="upload.name"
      :with-credentials="upload.withCredentials"
      :limit="Number(upload.limit)"
      :list-type="upload.listType"
      :on-preview="handlePreview"
      :on-remove="handleRemove"
      :before-upload="beforeUpload"
      :on-exceed="handleExceed"
      :on-success="handleSuccess"
      :on-error="handleError"
      ref= "uploader"
    >
      <el-button type="primary">点击上传</el-button>
      <template #tip>
        <div class="el-upload__tip">
          {{ upload.tip }}
        </div>
      </template>
    </el-upload>
    <el-dialog
      v-model="preview.visible"
      title="图片预览"
      width="45%"
      :before-close="handleClose"
    >
    <el-image style="width: 100%; height: 500px" :src="preview.url" fit="scale-down"/>
    </el-dialog>    
  </div>
    
    
  </template>
  <script>
  import { reactive, ref } from 'vue'
  import { ElMessage } from 'element-plus'
  import { isFunction, http } from '@/utils/tools'
  export default { 
    name: 'fileUpload',
    props: {
      config: {
        type: Object,
        default: () => {}
      }
    },
    setup(props, {emit}) {
      const preview = reactive({
        url: '',
        visible: false,
      })
      const { config } = props
      // const prevUrl = `${import.meta.env.VITE_BASE_API}`
      console.log('config----', config)
      const upload = {
        action: `${config?.url || '/upload/image'}`,
        name: config?.name || 'file',
        multiple: config?.multiple ?? false,
        accept: config?.accept || 'jpg,png',
        headers: config?.headers || {},
        data: config?.data || {},
        limit: config?.limit || 3,
        listType: config?.listType || "picture",
        withCredentials: config?.withCredentials ?? false,
        tip: config?.tip || '只能上传jpg/png文件，且小于500KB',
        // successCode: config?.successCode || '0',
        // responseStatusKey: config?.responseStatusKey || 'returnCode',
        successLogic: config?.successLogic || "obj?.returnCode == '0'",
        responseKey: config?.responseKey || 'resBody',
        urlDel: config?.urlDel,
        handleDel: config?.handleDelParams,
        successDelLogic: config?.successDelLogic || "obj?.returnCode == '0'",
      }
      let fileList = reactive([])
      const uploader = ref()
      const handleRemove = async (file, uploadFiles) => {
        console.log('fileList----', file, uploadFiles, fileList)
        if (upload.handleDel && isFunction(upload.handleDel)) {
          const params = upload.handleDel(file, uploadFiles)
          const res = await http.post(upload.urlDel, params, { headers: upload.headers })
          const isSuccess = res && new Function('obj', `return ${upload.successDelLogic}`)(res)
          if (!isSuccess) {
            ElMessage.error(`${file.name} 删除失败.`)
            return
          }
          ElMessage.success(`${file.name} 删除成功.`)
          fileList = fileList.filter(item => item.name !== file.name)
        }
        emit('change', fileList)
      }
      
      const handlePreview = (uploadFile) => {
        preview.url = uploadFile.url
        preview.visible = true
      }
      const handleSuccess = (response, file, uploadFiles) => {
        // if (response[upload.responseStatusKey] != upload.successCode) return
        const isSuccess = response && new Function('obj', `return ${upload.successLogic}`)(response)
        if (!isSuccess) {
          ElMessage.error(`${file.name} 上传失败.`)
          return
        }
        ElMessage.success(`${file.name} 上传成功.`)
        uploadFiles.length && uploadFiles.forEach(item => {
          const { response } = item
          fileList.push({
            name: item.name,
            size: item.size,
            url: response[upload.responseKey]?.url || item.url,
            response
          })
        })
        emit('change', fileList)
      }
      const handleError = (err, file, uploadFiles) => {
        ElMessage.error(`${file.name} 上传失败.`)
      }
    
      const handleExceed = (files, uploadFiles) => {
        ElMessage.warning(
          `最大限制只能上传${upload.limit}个文件，当前已选择${uploadFiles.length}个文件`
        )
      }
      
      const beforeUpload = file => {
        /* web端不允许重复上传 */
        const accept = upload.accept.split(',')
        const type = file.name.split('.').pop()
        const isExited = fileList.findIndex(item => item.name === file.name) > -1
        if (isExited) {
          ElMessage.warning('文件已存在!')
          return false
        } else  if (!accept.includes(type)) { /* 上传前格式校验 */
          ElMessage.warning('上传文件类型错误！')
          return false
        }else if (file?.size / 1024 / 1024 > 5) { /* 文件大小校验 */
          ElMessage.warning('文件大小不能超过5MB！')
          return false
        } else {
          return true
        }
      }
      const handleClose = () => {
        preview.visible = false
      }
      return {
        upload, handleClose, beforeUpload, handleExceed, handleError, handleSuccess, handleRemove, handlePreview, preview, fileList
      }
    }
  }
  </script>
  